﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NBusiness.VisualStudio.Commands;

namespace NBusiness.VisualStudio
{
    public static class CommandManager
    {
        private static Queue<ICommand> _queue = new Queue<ICommand>();

        public static void Queue(ICommand command)
        {
            if (command == null)
                throw new ArgumentNullException("command");

            command.Completed += new EventHandler(command_Completed);
            command.Initialize();
            lock (_queue)
            {
                _queue.Enqueue(command);
                if (_queue.Count == 1)
                    Execute(command);
            }
        }

        static void Execute(ICommand command)
        {
            Action action = new Action(command.Execute);
            action.BeginInvoke(new AsyncCallback(command_EndInvoke), action);
        }

        static void command_EndInvoke(IAsyncResult result)
        {
            Action action = result.AsyncState as Action;
            action.EndInvoke(result);
        }

        static void command_Completed(object sender, EventArgs e)
        {
            using (ICommand command = sender as ICommand)
            {
                command.Completed -= new EventHandler(command_Completed);
                lock (_queue)
                {
                    ICommand top = _queue.Dequeue();
                    System.Diagnostics.Debug.WriteLineIf(top != command, "Invalid command completed");

                    if (_queue.Count > 0)
                        Execute(_queue.Peek());
                }
            }
        }
    }
}
